﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IHISCETeim.Model;
using IHISCETeim.BLL;
using IHISCETeim.Library;
using FineUI;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Data;
using System.Text;
namespace IHISCETeim.Web.AgentSys.SvrMgr
{
    public partial class AgentQltySvrActEdit : AgentPageBase
    {

        protected override Permission[] PowerKey
        {
            get
            {
                return new Permission[] { Permission.修改,Permission.查看 };
            }
        }
        protected override string DWZRef
        {
            get { return "AgentQltySvrActList"; }
        }

        protected int QltyId {
            get {
                return GetRequestValue<int>("QltyId", 0);
            }
        }
        private AgentQltyInfo _objQlty = null;
        protected AgentQltyInfo objQlty
        {
            get {
                if (_objQlty == null)
                {
                    _objQlty = AgentQltyController.GetByQltyId(QltyId);
                }
                return _objQlty;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }
        private void LoadData()
        {
            btnClose.OnClientClick = GetCloseActiveTabScript();
          

            this.btnSaveClose.Hidden = this.btnEdit.Hidden = this.btnReject.Hidden = this.btnCancel.Hidden = this.btnAddNew.Hidden = this.btnMrgAccept.Hidden = this.btnMrgReject.Hidden = this.btnSendCCEmail.Hidden = !HasPower(Permission.修改);
           // this.btnEdit.Hidden = HasPower(Permission.经销商_品情_内部抄送审核);
            this.btnSendCCEmail.Enabled = HasPower(Permission.经销商_品情_内部抄送审核);

            this.CCPartEmail.Enabled = HasPower(Permission.经销商_品情_内部抄送审核);
            
           // this.btnSaveClose.Hidden = !HasPower(Permission.修改);
            //只有服务担当 以及 其上级才能修改
           int userId = objQlty.SrvActUserId;
           if (base.User.UserId != userId)
           {
               this.btnSaveClose.Enabled = false;
               this.btnReject.Enabled = false;
               this.btnCancel.Enabled = false;
               this.btnEdit.Enabled = false;
               this.btnAddNew.Enabled = false;


               AgentPowerConfigInfo power = new AgentPowerConfigInfo();
               while (true)
               {
                   power = AgentConfigController.GetByUserId(userId);
                   userId = AgentConfigController.GetById(power.ParId).UserId;
                   if (power.ID == 0)
                       break;
                   if (base.User.UserId == userId)
                   {
                       this.btnSaveClose.Enabled = true;
                       this.btnEdit.Enabled = true;
                       this.btnReject.Enabled = true;
                       this.btnAddNew.Enabled = true;
                       this.btnCancel.Enabled = true;
                       break;
                   }

               }

               //2015-08-10
               this.IsYanPao.Checked = UWarrantyCardController.GetBySerialNumber(objQlty.SerialNumber.ToUpper().Trim()).IsKeepSvr;
              


           }
               


            for (int imgIndex = 1; imgIndex <= 6; imgIndex++)
            {
                FineUI.FileUpload filePhotoControl = Panel4.FindControl("filePhoto" + imgIndex) as FineUI.FileUpload;
                filePhotoControl.Hidden =!HasPower(Permission.修改);
              
            }
            //如果 此品情单状态 不是 服务担当确认中 ,则需要提示是否修改再提交,再提交的话,则会重新走一遍流程.
            if (objQlty.ClaimState != IHISCETeim.Web.ClaimState.担当确认中.ToString())
            {
                this.btnSaveClose.Hidden = true;
                this.btnReject.Hidden = true;
                this.btnCancel.Hidden = true;
                this.btnEdit.Hidden = false;
                this.btnAddNew.Hidden = true;
                this.btnMrgAccept.Hidden = true;
                this.btnMrgReject.Hidden = true;
                // btnSaveClose.Hidden = true;
                // this.btnCancel.Hidden = true;
            }
            if (objQlty.ClaimState == IHISCETeim.Web.ClaimState.品情已确认.ToString())
            {
                this.btnSaveClose.Hidden = true;
                //this.btnReject.Hidden = true;
                this.btnCancel.Hidden = true;
                this.btnEdit.Hidden = !HasPower(Permission.经销商_品情_确认后修改);
                this.btnAddNew.Hidden = false;
                this.btnMrgAccept.Hidden = true;
                this.btnMrgReject.Hidden = true;
               // this.btnAddNew.Hidden = false;
                //this.btnReject.Hidden = true;
                //this.btnCancel.Hidden = true;


                AgentPowerConfigInfo powerObj = AgentConfigController.GetByUserId(base.User.UserId);
                if (powerObj.ShowClaimState == IHISCETeim.Web.ClaimState.服务经理审核中.ToString() || powerObj.ShowClaimState == IHISCETeim.Web.ClaimState.服务部长审核中.ToString())
                {
                    this.btnReject.Hidden = false;
                }
            }
            if (objQlty.ClaimState == IHISCETeim.Web.ClaimState.担当确认中.ToString())
            {
                this.btnSaveClose.Hidden = false;
                this.btnReject.Hidden = false;
                this.btnCancel.Hidden = false;
                this.btnEdit.Hidden = false;
                this.btnAddNew.Hidden = true;
                this.btnMrgAccept.Hidden = true;
                this.btnMrgReject.Hidden = true;
                //this.btnReject.Hidden = false;
            }
            if (objQlty.ClaimState == IHISCETeim.Web.ClaimState.服务经理审核中.ToString() || objQlty.ClaimState == IHISCETeim.Web.ClaimState.服务部长审核中.ToString() || objQlty.ClaimState == IHISCETeim.Web.ClaimState.技术经理审核中.ToString())
            {
                int tempUserId = 0;
                AgentPowerConfigInfo power = new AgentPowerConfigInfo();

                tempUserId = objQlty.SrvMangerUserId;
                while (true)
                {
                                     
                    if (base.User.UserId == tempUserId)
                    {
                        this.btnMrgAccept.Hidden = false;
                        this.btnMrgReject.Hidden = false;
                        break;
                    }
                    power = AgentConfigController.GetByUserId(tempUserId);  
                    tempUserId = AgentConfigController.GetById(power.ParId).UserId;
                    if (power.ID == 0)
                        break;
                }

                //if (User.UserId == AgentConfigController.GetTopSvrMgr(objQlty.SrvActUserId).UserId)
                //{
                //    this.btnMrgAccept.Hidden = false;
                //    this.btnMrgReject.Hidden = false;
                //}
                //else
                //{ 
                //    AgentPowerConfigInfo powerObj=  AgentConfigController.GetByUserId(base.User.UserId);
                //    if (powerObj.UserId == objQlty.SrvMangerUserId && powerObj.ShowClaimState == objQlty.ClaimState)
                //    {
                //        this.btnMrgAccept.Hidden = false;
                //        this.btnMrgReject.Hidden = false;
                //    }
                //}
            }
            //2015-01-26 一周回访由服务经理及服务部长处理
            this.IsVisit.Enabled = false;
            AgentPowerConfigInfo vPowerObj = AgentConfigController.GetByUserId(base.User.UserId);
            if (vPowerObj.ShowClaimState == IHISCETeim.Web.ClaimState.服务经理审核中.ToString() || vPowerObj.ShowClaimState == IHISCETeim.Web.ClaimState.服务部长审核中.ToString())
            {
               
                this.IsVisit.Enabled = true;
            }

            //
            string selectURL = String.Format("./SelectMainFault.aspx?ids=<script>{0}</script>", this.MainFault.GetValueReference());
            this.MainFaultText.OnClientTriggerClick = ViewImgWindow.GetSaveStateReference(MainFault.ClientID, MainFaultText.ClientID)
                    + ViewImgWindow.GetShowReference(selectURL, "选择故障分类");

            //历史故障列表
           // string selectURL2 = String.Format("./AgentQltyHistroyList.aspx?s={0}&id={1}", objQlty.SerialNumber,objQlty.QltyId);
           // this.histroyQlty.OnClientClick = ViewImgWindow.GetShowReference(selectURL2, "历史故障列表");

            //
            this.TriggerBox1.Text = string.Format("机器{0}的历史故障信息",objQlty.SerialNumber);
            string selectURL3 = String.Format("./AgentQltyHistroyList.aspx?s={0}&id={1}&oldClaimsNumber={2}", objQlty.SerialNumber, objQlty.QltyId, objQlty.ClaimsNumber);
            this.TriggerBox1.OnClientTriggerClick = ViewImgWindow.GetSaveStateReference(ClaimsNumber.ClientID)
                    + ViewImgWindow.GetShowReference(selectURL3, "历史故障列表(可选择品情进行附属品情操作)");
            LoadQltyInfo();           
        }

        private void LoadQltyInfo()
        {
            this.ClaimsNumber.Text = objQlty.ClaimsNumber;
            this.IssueDate.Text = objQlty.IssueDate.ToString("yyyy-MM-dd");
            this.AgentName.Text = objQlty.AgentName;
            this.SerialNumber.Text = objQlty.SerialNumber;
            this.MachineType.Text = objQlty.MachineType;
            this.CustomerName.Text = objQlty.CustomerName;
            this.CustomerMobile.Text = objQlty.CustomerMobile;
            this.IntoDate.Text =objQlty.IntoDate==DateTime.MinValue?"": objQlty.IntoDate.ToString("yyyy-MM-dd");
            this.IntoAddress.Text = objQlty.IntoAddress;
            this.FaultDate.Text = objQlty.FaultDate.ToString("yyyy-MM-dd");
            this.WorkHour.Text = objQlty.WorkHour.ToString("F0");
            this.ReportUser.Text = objQlty.ReportUser;
            this.ReportTel.Text = objQlty.ReportTel;
            this.MacNature.SelectedValue = objQlty.MacNature;
            this.IntoConditi.SelectedValue = objQlty.IntoConditi;
            this.IntoSpecial.SelectedValue = objQlty.IntoSpecial;
            this.DamagePartsNumber.Text = objQlty.DamagePartsNumber;
            this.HEFaultDescription.Text = objQlty.FaultDescription;
            this.MainFault.Text = objQlty.MainFaultID.ToString();
            this.MainFaultText.Text = AgentMainFaultControlller.GetById(objQlty.MainFaultID).Title;
            this.HEFaultReason.Text = objQlty.FaultReason ;
            this.HEProcessMode.Text = objQlty.ProcessMode;
            this.PartsAcceptAddress.Text = objQlty.PartsAcceptAddress;
            this.PartsAcceptName.Text = objQlty.PartsAcceptName;
            this.PartsAcceptTel.Text = objQlty.PartsAcceptTel;
            this.PartsAcceptDate.SelectedValue = objQlty.PartsAcceptDate;
            this.IsMTTR.Checked = objQlty.IsMTTR;
            this.IsYJGL.Checked = objQlty.IsYJGL;
            this.ReportType.SelectedValue = objQlty.ReportType;
            this.IsVisit.Checked = objQlty.IsVisit;
            this.SvrResult.Text = objQlty.SvrResult;
            this.SvrScheme.Text = objQlty.SvrScheme;
            this.IsNeedAppove.Checked = objQlty.IsNeedAppove;
            this.btnSendCCEmail.Hidden = !objQlty.IsNeedAppove;
            this.IsOldConfirm.Checked = objQlty.IsOldConfirm;
            this.NoNormative.Checked = objQlty.NoNormative;
            if (objQlty.IsAppove)
            {
                this.btnSendCCEmail.Hidden = true;
            }
            

            this.PartsSendDate.SelectedValue = objQlty.PartsSendDate;
            this.PartsSendType.SelectedValue = objQlty.PartsSendType;


            this.ClaimState.Text = objQlty.ClaimState;
           // this.CancelReason.Text = objQlty.CancelReason;
          //  this.IsCancelReason.Checked = objQlty.IsCancelReason;
          //  this.CancelReason.Readonly = objQlty.IsCancelReason;
           // this.RejectReason.Text = objQlty.RejectReason;
           // this.RejectReason.Readonly = !string.IsNullOrEmpty(objQlty.RejectReason);
            //
            List<AgentPowerConfigInfo> list = AgentConfigController.GetAllPowerConfig();
            list.Add(new AgentPowerConfigInfo() { UserId = 0, RealName = "空" });
            this.AgentSvrUserId.DataSource = list;
            this.AgentSvrUserId.DataBind();
            AgentSvrUserId.SelectedValue = "0";
            this.AgentSvrTel.Text = "";// objQlty.AgentSvrTel;
            if (objQlty.AgentSvrUserId < 0)
            {
                //如果此当服务担当不等于当前人员,则用当前人员进行处理
                if (objQlty.SrvActUserId != this.User.UserId)
                {
                    AgentSvrUserId.SelectedValue = this.User.UserId.ToString();
                    this.AgentSvrTel.Text = OUserController.GetById(this.User.UserId).Mobile;
                }
            }
            else
            {
                AgentSvrUserId.SelectedValue = objQlty.AgentSvrUserId.ToString();
                this.AgentSvrTel.Text =  objQlty.AgentSvrTel;
            }
           


            ///加载图片
            List<AgentQltyImgInfo> listImg = AgentQltyController.GetAllImgByQltyId_0(QltyId);
            for (int imgIndex = 1; imgIndex <= listImg.Count-1; imgIndex++)
            {                       
                FineUI.Image imgRelativelyControl = Panel4.FindControl("imgRelatively" + imgIndex) as FineUI.Image;
                FineUI.TextBox ImgTitleControl = Panel4.FindControl("ImgTitle" + imgIndex) as FineUI.TextBox;

                ImgTitleControl.Text = listImg[imgIndex - 1].Title;
                imgRelativelyControl.ImageUrl = listImg[imgIndex - 1].IMGRelatively;
            }
            try
            {
                this.fileOtherDownLoad.NavigateUrl = listImg[6].IMGRelatively;
            }
            catch { }

            //2016-04-06 加入 IHISCE服务部品情回复 图片
            listImg = AgentQltyController.GetAllImgByQltyId_2(QltyId);
            for (int imgIndex = 1; imgIndex <= listImg.Count - 1; imgIndex++)
            {
                FineUI.Image imgRelativelyControl = Panel8.FindControl("SvrResultImg" + imgIndex) as FineUI.Image;
                FineUI.TextBox ImgTitleControl = Panel8.FindControl("SvrResultImgTitle" + imgIndex) as FineUI.TextBox;

                ImgTitleControl.Text = listImg[imgIndex - 1].Title;
                imgRelativelyControl.ImageUrl = listImg[imgIndex - 1].IMGRelatively;
            }
            try
            {
                this.SvrResultImg3.NavigateUrl = listImg[2].IMGRelatively;
            }
            catch { }
            //2016-04-06 加入 内部通报与对策图
            listImg = AgentQltyController.GetAllImgByQltyId_3(QltyId);
            for (int imgIndex = 1; imgIndex <= listImg.Count - 1; imgIndex++)
            {
                FineUI.Image imgRelativelyControl = Panel9.FindControl("SvrSchemeImg" + imgIndex) as FineUI.Image;
                FineUI.TextBox ImgTitleControl = Panel9.FindControl("SvrSchemeImgTitle" + imgIndex) as FineUI.TextBox;

                ImgTitleControl.Text = listImg[imgIndex - 1].Title;
                imgRelativelyControl.ImageUrl = listImg[imgIndex - 1].IMGRelatively;
            }
            try
            {
                this.SvrSchemeImg3.NavigateUrl = listImg[2].IMGRelatively;
            }
            catch { }



            //加载配件
            List<AgentQltyPartsInfo> listParts = AgentQltyController.GetAllPartsByQltyId(QltyId);
            //2015-6-12加入配件索赔金额限制
            decimal _cSumPrice = listParts.Sum(e => e.LastPurPrice * e.Quantity);
            if (_cSumPrice >= AgentConfigController.QltyAlarmMoney)
            {
                this.AlarmText.Text = string.Format("注意:此索赔单配件总成本已超过【{0}】元", AgentConfigController.QltyAlarmMoney);
                this.AlarmText.Hidden = objQlty.ClaimState != IHISCETeim.Web.ClaimState.服务部长审核中.ToString();
                this.AlarmText.EncodeText = true;
            }
            int _zeroPart=listParts.FindAll(e=>e.LastPurPrice<=0).Count();
            if (_zeroPart > 0)
            {
                this.ZeroPartNum.Text = string.Format("此索赔单有【{0}】个配件的成本为0", _zeroPart);
            }


            if (listParts.Count < 20)
            { 
                int addNum=20-listParts.Count ;
                while (addNum > 0)
                {
                    listParts.Add(new AgentQltyPartsInfo());
                    addNum = addNum - 1;
                }
            }
            this.grdAgentQltyParts.DataSource = listParts;
            this.grdAgentQltyParts.DataBind();

            


            DataTable dtreject = AgentQltyController.AgentQltyReject_GetAllByQltyId(QltyId);
            this.gdReject.DataSource = dtreject.Select("FromType=0") ;
            this.gdReject.DataBind();

            this.gdShenHe.DataSource = dtreject.Select("FromType=1");
            this.gdShenHe.DataBind();

            //2014-10-11 加入抄送部门
            this.CCPartEmail.DataTextField = "ccpartName";
            this.CCPartEmail.DataValueField = "ccpartKey";
            this.CCPartEmail.DataSource = AgentConfigController.GetQltyccPartList();
            this.CCPartEmail.DataBind();
            this.CCPartEmail.SelectedValueArray = objQlty.CCPartEmail.Split(',');
            

        }
        protected void filePhoto1_FileSelected(object sender, EventArgs e)
        {
            FineUI.FileUpload FileUpladControl = sender as FineUI.FileUpload;
            string cIndex = FileUpladControl.EmptyText;
            FineUI.Image imgRelativelyControl = (FileUpladControl.Parent).FindControl(cIndex) as FineUI.Image;



            if (FileUpladControl.HasFile)
            {
                string fileName = FileUpladControl.ShortFileName;

                if (!ValidateFileType(fileName))
                {
                    Alert.Show("无效的文件类型！");
                    return;
                }


                fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
                fileName = DateTime.Now.Ticks.ToString() + "_" + fileName;

                string path = GetUpLoadFilePath(User.Department);
                FileUpladControl.SaveAs(Server.MapPath(path + fileName));

                imgRelativelyControl.ImageUrl = path + fileName;

                // 清空文件上传组件
                FileUpladControl.Reset();
            }
        }
        protected void fileOther_FileSelected(object sender, EventArgs e)
        {
            if (fileOther.HasFile)
            {
                string fileName = fileOther.ShortFileName;

                if (!ValidateFileType(fileName))
                {
                    Alert.Show("无效的文件类型！");
                    return;
                }


                fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
                fileName = DateTime.Now.Ticks.ToString() + "_" + fileName;

                string path = GetUpLoadFilePath(User.Department);
                fileOther.SaveAs(Server.MapPath(path + fileName));

               // fileOther.EmptyText = path + fileName;
               // fileOther.ShowEmptyLabel = false;
                fileOtherDownLoad.Hidden = false;
                fileOtherDownLoad.NavigateUrl = path + fileName;
                fileOtherDownLoad.Text = fileName;
              //  fileOther.Label = path + fileName;
              
                // 清空文件上传组件
                fileOther.Reset();
            }
        }

        protected void grdAgentQltyParts_PreRowDataBound(object sender, GridPreRowEventArgs e)
        {
            AgentQltyPartsInfo itmData = e.DataItem as AgentQltyPartsInfo;
           // itmData.ItemCode
            if(!string.IsNullOrEmpty(itmData.ItemCode))
            { 
                if( SBOController.GetHaveItemCode(itmData.ItemCode)=="")
                { 
                    System.Web.UI.WebControls.TextBox tbItemCode = grdAgentQltyParts.Rows[e.RowIndex].FindControl("tbItemCode") as System.Web.UI.WebControls.TextBox;
                    tbItemCode.BackColor = System.Drawing.Color.Red;
                }
            }
        }

        protected void grdAgentQltyParts_RowDataBound(object sender, GridRowEventArgs e)
        {
            AgentQltyPartsInfo itmData = e.DataItem as AgentQltyPartsInfo;
            System.Web.UI.WebControls.DropDownList ddl = grdAgentQltyParts.Rows[e.RowIndex].FindControl("ddlPartsDemand") as System.Web.UI.WebControls.DropDownList;
            ddl.SelectedValue = itmData.PartsDemand;

        }

        /// <summary>
        /// 处理品情
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            int reVal = save(2);
            if (reVal == -99)
            {
                return;
            }
            switch (reVal)
            {               
                case -1:                   
                    Alert.Show("必需选择一项 配件发送日期、方式");                   
                    break;
                case 0:
                    Alert.Show("品情处理失败,请通知IT部", "提示", MessageBoxIcon.Error);                    
                    break;
                case 1:
                    Alert.Show("品情已提交到上级审核,请留意邮件通知.", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());
                    break;
                case 2:
                    Alert.Show("品情已确认,系统已通知相应人员发货,请留意邮件通知.", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());
                    break;
                case 3:
                    Alert.Show("品情已确认.", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());
                    break;
                case 4:
                    Alert.Show("品情已取消,已邮件通知相关经销商内勤人员.", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());
                    break;
                default:
                    Alert.Show("未处理错误，请通知IT部,错误代码为" + reVal.ToString(), MessageBoxIcon.Error);
                    break;
            }

           // PageContext.RegisterStartupScript(GetCloseActiveTabRefreshScript);
            //ActiveWindow
            //PageContext.Refresh(DWZRef);
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            int r = save(1);
            if (r == -99)
            {
                return;
            }
            if (r == 1)
            {
                Alert.Show("成功修改品情信息", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());
            }
            else {
                if (r == -1)
                    Alert.Show("必需选择一项 配件发送日期、方式");
                else
                    Alert.Show("修改品情信息失败.", "提示", MessageBoxIcon.Error);
            }

        }

        /// <summary>
        /// 1为保存修改 2为提交审核 3 为添加附属品情
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
       private int save(int type)
       {
            AgentQltyInfo obj = objQlty;
            obj.QltyId = QltyId;
            obj.ClaimsNumber = this.ClaimsNumber.Text;
            obj.IssueDate = objQlty.IssueDate;// Convert.ToDateTime(this.IssueDate.Text);
            obj.SerialNumber = this.SerialNumber.Text;
            obj.AgentName = this.AgentName.Text;
            obj.MachineType = this.MachineType.Text;
            obj.CustomerName = this.CustomerName.Text;
            obj.CustomerMobile = this.CustomerMobile.Text;
            obj.IntoDate = string.IsNullOrEmpty(this.IntoDate.Text) ? DateTime.MinValue : Convert.ToDateTime(this.IntoDate.Text);
            obj.IntoAddress = this.IntoAddress.Text;
            obj.FaultDate = objQlty.FaultDate;// Convert.ToDateTime(this.FaultDate.Text);
            obj.WorkHour = Convert.ToDecimal(this.WorkHour.Text.Trim());
            obj.ReportUser = this.ReportUser.Text;
            obj.ReportTel = this.ReportTel.Text;
            obj.MacNature = this.MacNature.SelectedValue;
            obj.IntoConditi = this.IntoConditi.SelectedValue;
            obj.IntoSpecial = this.IntoSpecial.SelectedValue;
            obj.DamagePartsNumber = this.DamagePartsNumber.Text;
            obj.FaultDescription = StringHelper.StripTags(this.HEFaultDescription.Text,false);
            obj.MainFaultID =Convert.ToInt32( this.MainFault.Text);
            obj.FaultReason = StringHelper.StripTags( this.HEFaultReason.Text,false);
            obj.ProcessMode =StringHelper.StripTags(this.HEProcessMode.Text,false);
            obj.PartsAcceptAddress = this.PartsAcceptAddress.Text;
            obj.PartsAcceptName = this.PartsAcceptName.Text;
            obj.PartsAcceptTel = this.PartsAcceptTel.Text;
            obj.PartsAcceptDate = this.PartsAcceptDate.SelectedValue;
            obj.IsMTTR = this.IsMTTR.Checked;
            obj.ReportType = this.ReportType.SelectedValue;
            obj.IsVisit = this.IsVisit.Checked ;
            obj.SvrResult =StringHelper.StripTags( this.SvrResult.Text,false);
            obj.SvrScheme = StringHelper.StripTags(this.SvrScheme.Text,false);
            obj.IsNeedAppove = this.IsNeedAppove.Checked;
            obj.IsYJGL = this.IsYJGL.Checked;
            obj.PartsSendDate = this.PartsSendDate.SelectedValue;
            obj.PartsSendType = this.PartsSendType.SelectedValue;
            obj.IsOldConfirm = this.IsOldConfirm.Checked;
            obj.CCPartEmail = String.Join(",", this.CCPartEmail.SelectedValueArray);                 
            //obj.SrvMangerUserId = AgentConfigController.SvrManagerUserId;
            //obj.ClaimState = ClaimState.担当确认中.ToString();
            //obj.RejectReason = "";
            //obj.IsCancelReason = this.IsCancelReason.Checked;
            //obj.CancelReason = this.IsCancelReason.Checked ? this.CancelReason.Text : "";
            obj.AgentSvrUserId = Convert.ToInt32(this.AgentSvrUserId.SelectedValue);
            obj.AgentSvrRealName = this.AgentSvrUserId.SelectedText;
            obj.AgentSvrTel = this.AgentSvrTel.Text;
            obj.NoNormative = this.NoNormative.Checked;
            //加载图片信息
            //AgentQltyImgInfo imgObj = new AgentQltyImgInfo();
            List<AgentQltyImgInfo> imgList = new List<AgentQltyImgInfo>();
            AgentQltyImgInfo imgObj =null;
            for (int imgIndex = 1; imgIndex <= 6; imgIndex++)
            {
                imgObj = new AgentQltyImgInfo();
                FineUI.Image imgRelativelyControl = Panel4.FindControl("imgRelatively" + imgIndex) as FineUI.Image;
                FineUI.TextBox ImgTitleControl = Panel4.FindControl("ImgTitle" + imgIndex) as FineUI.TextBox;
                imgObj.Title = ImgTitleControl.Text;
                imgObj.IMGRelatively = imgRelativelyControl.ImageUrl;
                imgObj.FileIndex = imgIndex;
                imgObj.FromType = 0;
                imgList.Add(imgObj);
            }
            imgObj = new AgentQltyImgInfo();
            imgObj.Title = "其它文件";
            imgObj.IMGRelatively = fileOtherDownLoad.NavigateUrl;
            imgObj.FileIndex = 7;
            imgObj.FromType = 0;
            imgList.Add(imgObj);
            //2016-04-06 加入 IHISCE服务部品情回复 图片
            for (int imgIndex = 1; imgIndex <= 2; imgIndex++)
            {
                imgObj = new AgentQltyImgInfo();
                FineUI.Image imgRelativelyControl = Panel8.FindControl("SvrResultImg" + imgIndex) as FineUI.Image;
                FineUI.TextBox ImgTitleControl = Panel8.FindControl("SvrResultImgTitle" + imgIndex) as FineUI.TextBox;
                imgObj.Title = ImgTitleControl.Text;
                imgObj.IMGRelatively = imgRelativelyControl.ImageUrl;
                imgObj.FileIndex = imgIndex;
                imgObj.FromType = 2;
                imgList.Add(imgObj);
            }
            imgObj = new AgentQltyImgInfo();
            imgObj.Title = "其它文件";
            imgObj.IMGRelatively = SvrResultImg3.NavigateUrl;
            imgObj.FileIndex =3;
            imgObj.FromType = 2;
            imgList.Add(imgObj);
            //2016-04-06 
            for (int imgIndex = 1; imgIndex <= 2; imgIndex++)
            {
                imgObj = new AgentQltyImgInfo();
                FineUI.Image imgRelativelyControl = Panel9.FindControl("SvrSchemeImg" + imgIndex) as FineUI.Image;
                FineUI.TextBox ImgTitleControl = Panel9.FindControl("SvrSchemeImgTitle" + imgIndex) as FineUI.TextBox;
                imgObj.Title = ImgTitleControl.Text;
                imgObj.IMGRelatively = imgRelativelyControl.ImageUrl;
                imgObj.FileIndex = imgIndex;
                imgObj.FromType = 3;
                imgList.Add(imgObj);
            }
            imgObj = new AgentQltyImgInfo();
            imgObj.Title = "其它文件";
            imgObj.IMGRelatively = SvrSchemeImg3.NavigateUrl;
            imgObj.FileIndex = 3;
            imgObj.FromType = 3;
            imgList.Add(imgObj);

            //获取配件信息
            List<AgentQltyPartsInfo> partsList = new List<AgentQltyPartsInfo>();

            string checkitemcode = "";
            string notbeiyouerr = "";
            for (int i = 0, count = this.grdAgentQltyParts.Rows.Count; i < count; i++)
            {
                AgentQltyPartsInfo pobj = new AgentQltyPartsInfo();

                GridRow row = grdAgentQltyParts.Rows[i];
                System.Web.UI.WebControls.TextBox tbItemCode = (System.Web.UI.WebControls.TextBox)row.FindControl("tbItemCode");
                System.Web.UI.WebControls.TextBox tbDscription = (System.Web.UI.WebControls.TextBox)row.FindControl("tbDscription");
                FineUI.TextBox tbQuantity = (FineUI.TextBox)row.FindControl("Quantity");
                System.Web.UI.WebControls.DropDownList ddlPartsDemand = (System.Web.UI.WebControls.DropDownList)row.FindControl("ddlPartsDemand");
                FineUI.TextBox tbRemark = (FineUI.TextBox)row.FindControl("Remark");
                System.Web.UI.WebControls.CheckBox cbInStock = (System.Web.UI.WebControls.CheckBox)row.FindControl("InStock");
                System.Web.UI.WebControls.CheckBox cbIsSPZGL = (System.Web.UI.WebControls.CheckBox)row.FindControl("IsSPZGL");

                if (!string.IsNullOrEmpty(tbItemCode.Text))
                {
                    if (SBOController.GetHaveItemCode(tbItemCode.Text.Trim()) == "")
                    {
                        checkitemcode += string.Format("<b>第{0}行</b>:【{1}】　{2}<br/>", i + 1, tbItemCode.Text.Trim(),tbDscription.Text.Trim());
                        continue;
                    }
                    

                    pobj.ItemCode = tbItemCode.Text.Trim();
                    pobj.Dscription = tbDscription.Text.Trim();
                    pobj.Quantity = Convert.ToDecimal(tbQuantity.Text.Trim());
                    pobj.PartsDemand = ddlPartsDemand.SelectedValue;
                    pobj.LastPurPrice = Convert.ToDecimal(SBOController.GetOITMLastPurPrice(pobj.ItemCode));
                    pobj.Remark = tbRemark.Text;
                    pobj.InStock = cbInStock.Checked;
                    pobj.IsSPZGL = cbIsSPZGL.Checked;
                    partsList.Add(pobj);
                    //2015-10-16 备用件一定要填备注
                    if (pobj.PartsDemand == "备用件发货")
                    {
                        if (pobj.Remark.IndexOf("索赔") == -1 && pobj.Remark.IndexOf("服务支持件") == -1)
                        {
                            notbeiyouerr += string.Format("<b>第{0}行</b>:【{1}】配件需求为 备用件发货,必需添写是索赔还是服务支持件的备注<br/>", i + 1, tbItemCode.Text.Trim());
                        }
                    }
                }

            }
            if (!string.IsNullOrEmpty(checkitemcode))
            {
                Alert.Show("以下配件不存在ERP系统中,请重新确认:<br/>"+checkitemcode);
                return -99;//表示有配件在ERP系统中不不存在
            }
            if (!string.IsNullOrEmpty(notbeiyouerr))
            {
                Alert.Show(notbeiyouerr);
                return -99;//表示有备注填写方法不正确
            }
            //配件发送方式及日期填写判断2014-09-15
            string _PartsRequestType = AgentQltyController.GetPartsRequestType(partsList);
            if (_PartsRequestType == "索赔发货" || _PartsRequestType=="供应商发货")
            { 
               // obj.PartsSendDate,obj.PartsSendType
                if (string.IsNullOrEmpty(obj.PartsSendDate) || string.IsNullOrEmpty(obj.PartsSendType))
                {
                    //Alert.Show("必需选择一项 配件发送日期、方式");
                    return -1;
                }
            }
            //return 0;
            List<AgentQltyRejectInfo> listReject = new List<AgentQltyRejectInfo>();
            AgentQltyRejectInfo objReject = null;
            switch (type)
            { 
                case 1:
                    return AgentQltyController.Edit(base.User.UserId, obj, imgList, partsList);
                    break;
                case 2://提交确认品情
                    //2015-02-08 加入审核记录
                    objReject = new AgentQltyRejectInfo();
                    objReject.RejectDate = DateTime.Now;
                    objReject.RejectRealName = base.User.RealName;
                    objReject.RejectReason = "服务担当通过审核";
                    objReject.FromType =1;

                    return AgentQltyController.SvrActEdit(0, objReject, base.User.UserId, obj, imgList, partsList);
                    break;
                case 3://生成附属品情
                    obj.ClaimState = IHISCETeim.Web.ClaimState.担当确认中.ToString();
                    obj.ClaimsNumber = AgentQltyController.GetNewClaimsNumber( objQlty.ClaimsNumber);
                    obj.ClaimState = IHISCETeim.Web.ClaimState.担当确认中.ToString();
                    return AgentQltyController.Add(obj, imgList, partsList,true);
                    break;
                case 4://驳回品情
                    objReject = new AgentQltyRejectInfo();
                    objReject.RejectDate = DateTime.Now;
                    objReject.RejectRealName = base.User.RealName;
                    objReject.RejectReason = this.RejectReason.Text;
                    objReject.TelRemark = this.TelRemark.SelectedText;
                    objReject.FromType =0;
                    obj.RejectReason = this.RejectReason.Text;
                    
                    return AgentQltyController.SvrActEdit(1, objReject,base.User.UserId, obj, imgList, partsList);
                    break;
                case 5://品情拒培
                    obj.ClaimState = IHISCETeim.Web.ClaimState.品情拒赔.ToString();
                    return AgentQltyController.SvrActEdit(2, null, base.User.UserId, obj, imgList, partsList);

                case 10://服务经理及部长审核，通过
                    //2015-02-08 加入审核记录
                    objReject = new AgentQltyRejectInfo();
                    objReject.RejectDate = DateTime.Now;
                    objReject.RejectRealName = base.User.RealName;
                    objReject.RejectReason = "技术经理、服务经理或部长通过审核";
                    objReject.FromType = 1;
                    return AgentQltyController.SvrMgrEdit(true, objReject, obj, imgList, partsList);
                    break;
                case 11://服务经理及部长审核，拒绝
                    objReject = new AgentQltyRejectInfo();
                    objReject.RejectDate = DateTime.Now;
                    objReject.RejectRealName = base.User.RealName;
                    objReject.RejectReason = this.RejectReason.Text;
                    objReject.FromType = 0;
                    obj.RejectReason =  this.RejectReason.Text;//驳回原因

                    return AgentQltyController.SvrMgrEdit(false, objReject, obj, imgList, partsList);
                    break;
                default:
                    break;
            }
            return 0;
       }

       protected void btnAddNew_Click(object sender, EventArgs e)
       {
           //重新生成新品情
          int r= save(3);

          if (r == -99)
          {
              return;
          }
          if (r > 0)
          {
              Alert.Show("已成功提交附属品情", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());             
          }
          else
          {
              if (r == -1)
                  Alert.Show("必需选择一项 配件发送日期、方式");
              else
                Alert.Show("提交附属品情失败.", "提示", MessageBoxIcon.Error);
          }
       }

        /// <summary>
        /// 驳回品情
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
       protected void btnReject_Click(object sender, EventArgs e)
       {
           if (string.IsNullOrEmpty(this.RejectReason.Text))
           {
               Alert.Show("请输入驳回原因");
               this.RejectReason.Focus();
               return;
           }
            if (string.IsNullOrEmpty(this.TelRemark.SelectedText))
            {
                Alert.Show("请选择电话沟通项目");
                this.TelRemark.Focus();
                return;
            }

            int reVal = save(4);
            if (reVal == -99)
            {
                return;
            }
            switch (reVal)
           {
               case -1:
                   Alert.Show("必需选择一项 配件发送日期、方式");
                   break;
               case 0:
                   Alert.Show("品情处理失败,请通知IT部", "提示", MessageBoxIcon.Error);
                   break;
  
               case 4:
                   Alert.Show("品情已驳回,已邮件通知相关经销商内勤人员及服务担当.", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());
                   break;
               default:
                   Alert.Show("未处理错误，请通知IT部,错误代码为" + reVal.ToString(), MessageBoxIcon.Error);
                   break;
           }
       }

       protected void btnCancel_Click(object sender, EventArgs e)
       {
           //if (string.IsNullOrEmpty(this.RejectReason.Text))
           //{
           //    Alert.Show("请输入驳回原因");
           //    this.RejectReason.Focus();
           //    return;
           //}


           int reVal = save(5);
            if (reVal == -99)
            {
                return;
            }
            switch (reVal)
           {

               case -1:
                   Alert.Show("必需选择一项 配件发送日期、方式", MessageBoxIcon.Error);   
                   break;              
               case 0:
                   Alert.Show("品情处理失败,请通知IT部", "提示", MessageBoxIcon.Error);
                   break;

               case 5:
                   Alert.Show("品情已拒赔,已邮件通知相关经销商内勤人员.", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());
                   break;
               default:
                   Alert.Show("未处理错误，请通知IT部,错误代码为" + reVal.ToString(), MessageBoxIcon.Error);  
                   break;
           }
       }

       protected void btnSendCCEmail_Click(object sender, EventArgs e)
       {

           //Alert.Show("功能开发中...");
          // return;
           int reVal = AgentQltyController.UpdateApproveScheme(QltyId, CCPartEmail.SelectedValueArray, this.SvrScheme.Text);
            switch (reVal)
            {
                case -1:
                    Alert.Show("提交处理失败,已有人抢先一步帮你审核并抄送相关部门了,你不用再执行.", "提示", MessageBoxIcon.Error);
                    break;
                case 0:
                    Alert.Show("提交处理失败,请通知IT部", "提示", MessageBoxIcon.Error);
                    break;
                case 1:
                    Alert.Show("已确认审核并抄送相关部门.", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());
                    break;
                default:
                    Alert.Show("未处理错误，请通知IT部,错误代码为" + reVal.ToString(), MessageBoxIcon.Error);
                    break;
            }
       }

       protected void DelteImage_Click(object sender, EventArgs e)
       {
           if (!HasPower(Permission.修改))
               return;
           FineUI.LinkButton btnControl = sender as FineUI.LinkButton;
           string cIndex = btnControl.TabIndex.ToString();
           if (cIndex == "7")
           {
               fileOtherDownLoad.Text = "原文件下载";
               fileOtherDownLoad.NavigateUrl = "";
           }
           else { 
            FineUI.Image imgRelativelyControl = Panel4.FindControl("imgRelatively" + cIndex) as FineUI.Image;
            imgRelativelyControl.ImageUrl = "/res/blank.png";
           }
       }

       protected void btnMrgAccept_Click(object sender, EventArgs e)
       {
           int reVal = save(10);
            if (reVal == -99)
            {
                return;
            }
            switch (reVal)
           {
               case 0:
                   Alert.Show("品情处理失败,请通知IT部", "提示", MessageBoxIcon.Error);
                   break;
               case 1:
                   Alert.Show("品情已提交到上级审核.", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());
                   break;
               case 2:
                   Alert.Show("品情已确认,系统已通知相应人员发货,请留意邮件通知.", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());
                   break;
               case 3:
                   Alert.Show("品情已确认.", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());
                   break;
               default:
                   Alert.Show("未处理错误，请通知IT部,错误代码为" + reVal.ToString(), MessageBoxIcon.Error);
                   break;
           }
       }

       protected void btnMrgReject_Click(object sender, EventArgs e)
       {
           if (string.IsNullOrEmpty(this.RejectReason.Text))
           {
               this.RejectReason.Focus();
               Alert.Show("请输入驳回原因.");
               return;
           }
           int reVal = save(11);
            if (reVal == -99)
            {
                return;
            }
            switch (reVal)
           {
               case 0:
                   Alert.Show("品情处理失败,请通知IT部", "提示", MessageBoxIcon.Error);
                   break;             
               case 5:
                   Alert.Show("品情已驳回,系统已邮件通知相应的服务担当", "提示", MessageBoxIcon.Information, GetCloseReloadActiveTabScript());
                   break;
               default:
                   Alert.Show("未处理错误，请通知IT部,错误代码为" + reVal.ToString(), MessageBoxIcon.Error);
                   break;
           }
       }

       protected void SvrResultDelteImage_Click(object sender, EventArgs e)
        {
            if (!HasPower(Permission.修改))
                return;
            FineUI.LinkButton btnControl = sender as FineUI.LinkButton;
            string cIndex = btnControl.TabIndex.ToString();
            if (cIndex == "3")
            {
                SvrResultImg3.Text = "原文件下载";
                SvrResultImg3.NavigateUrl = "";
            }
            else {
                FineUI.Image imgRelativelyControl = Panel8.FindControl("SvrResultImg" + cIndex) as FineUI.Image;
                imgRelativelyControl.ImageUrl = "/res/blank.png";
            }
        }
       
        protected void SvrResultfileOther_FileSelected(object sender, EventArgs e)
        {
            if (SvrResultFileUpload3.HasFile)
            {
                string fileName = SvrResultFileUpload3.ShortFileName;

                if (!ValidateFileType(fileName))
                {
                    Alert.Show("无效的文件类型！");
                    return;
                }


                fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
                fileName = DateTime.Now.Ticks.ToString() + "_" + fileName;

                string path = GetUpLoadFilePath(User.Department);
                SvrResultFileUpload3.SaveAs(Server.MapPath(path + fileName));

                // fileOther.EmptyText = path + fileName;
                // fileOther.ShowEmptyLabel = false;
                SvrResultImg3.Hidden = false;
                SvrResultImg3.NavigateUrl = path + fileName;
                SvrResultImg3.Text = fileName;
                //  fileOther.Label = path + fileName;

                // 清空文件上传组件
                SvrResultFileUpload3.Reset();
            }
        }

        protected void SvrSchemeDelteImage_Click(object sender, EventArgs e)
        {
            if (!HasPower(Permission.修改))
                return;
            FineUI.LinkButton btnControl = sender as FineUI.LinkButton;
            string cIndex = btnControl.TabIndex.ToString();
            if (cIndex == "3")
            {
                SvrSchemeImg3.Text = "原文件下载";
                SvrSchemeImg3.NavigateUrl = "";
            }
            else {
                FineUI.Image imgRelativelyControl = Panel9.FindControl("SvrSchemeImg" + cIndex) as FineUI.Image;
                imgRelativelyControl.ImageUrl = "/res/blank.png";
            }
        }

        protected void SvrSchemefileOther_FileSelected(object sender, EventArgs e)
        {
            if (SvrSchemeFileUpload3.HasFile)
            {
                string fileName = SvrSchemeFileUpload3.ShortFileName;

                if (!ValidateFileType(fileName))
                {
                    Alert.Show("无效的文件类型！");
                    return;
                }


                fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
                fileName = DateTime.Now.Ticks.ToString() + "_" + fileName;

                string path = GetUpLoadFilePath(User.Department);
                SvrSchemeFileUpload3.SaveAs(Server.MapPath(path + fileName));

                SvrSchemeImg3.Hidden = false;
                SvrSchemeImg3.NavigateUrl = path + fileName;
                SvrSchemeImg3.Text = fileName;

                // 清空文件上传组件
                SvrSchemeFileUpload3.Reset();
            }
        }
    }
}